import os
import sys
import shutil


CLIENT_MAIN_FILE_PATH = "Client/main.py"
SERVER_MAIN_FILE_PATH = "Server/main.py"

FOLDER_TO_DEL = ("build", "dist")
FILES_TO_DEL = (".spec", ".vbs")


def clear():
    print("\tCLEANING")
    deleted_files = 0
    deleted_folders = 0
    root = os.getcwd()

    for _, dirs, files in os.walk(root):
        for name in dirs:
            if name in FOLDER_TO_DEL:
                shutil.rmtree(os.path.join(root, name))
                deleted_folders += 1

        for ending in FILES_TO_DEL:
            for name in files:
                if name.endswith(ending):
                    os.remove(os.path.join(root, name))
                    deleted_files += 1

    print("Folders deleted: ", deleted_folders)
    print("Files deleted:", deleted_files)


def build_client(debug, filename="client.exe"):
    command = "pyinstaller --onefile "

    if not debug:
        command += "--noconsole "

    command += CLIENT_MAIN_FILE_PATH
    os.system(command)

    # TODO: move file and rename
    root = os.getcwd()
    shutil.move(os.path.join(root, f"dist\\main.exe"),
                os.path.join(root, filename))


def build_server(debug, filename="server.exe"):
    command = "pyinstaller --onefile "

    if not debug:
        command += "--noconsole "

    command += CLIENT_MAIN_FILE_PATH
    os.system(command)

    # TODO: move file and rename
    root = os.getcwd()
    shutil.move(os.path.join(root, f"dist\\main.exe"),
                os.path.join(root, filename))

def main(args):
    # TODO add icon changer
    BUILD_CLIENT = True
    BUILD_SERVER = True

    CLEAR = False
    DEBUG = False

    for raw_key in args[1:]:
        key = raw_key.lower()
        
        if key == "--clear" or key == "-c":
            CLEAR = True

        elif key == "--debug" or key == "-d":
            DEBUG = True

        elif key == "--build-only-server" or key == "-bos":
            BUILD_CLIENT = False
            BUILD_SERVER = True

        elif key == "--build-only-client" or key == "-boc":
            BUILD_CLIENT = True
            BUILD_SERVER = False

        else:
            raise KeyError(f"Unknown key: {key}")


    if BUILD_CLIENT:
        build_client(DEBUG)
    
    if BUILD_SERVER:
        build_server(DEBUG)

    if CLEAR:
        clear()


if __name__ == "__main__":
    main(sys.argv)
